from asyncpg import UniqueViolationError

from utils.db_api.db_gino import db
from utils.db_api.schemas.user import User


async def add_user(user_id: int, first_name: str, last_name: str, username: str, status: str,
                   subscribed: bool, ipss_test: int, qol_test: int, gender: str, age: str):
    try:
        user = User(user_id=user_id, first_name=first_name, last_name=last_name, username=username, status=status,
                    subscribed=subscribed, ipss_test=ipss_test, qol_test=qol_test,
                    gender=gender, age=age)
        await user.create()
    except UniqueViolationError:
        print('Пользователь не добавлен')


async def select_all_users():
    users = await User.query.gino.all()
    return users


async def count_users():
    count = await db.func.count(User.user_id).gino.scalar()
    return count


async def select_user(user_id):
    user = await User.query.where(User.user_id == user_id).gino.first()
    return user


async def update_user_sub(user_id, new_sub):
    user = await select_user(user_id)
    await user.update(subscribed=new_sub).apply()


async def update_user_gen(user_id, new_gen):
    user = await select_user(user_id)
    await user.update(gender=new_gen).apply()


async def update_user_age(user_id, new_age):
    user = await select_user(user_id)
    await user.update(age=new_age).apply()


async def update_user_ipss(user_id, new_ipss):
    user = await select_user(user_id)
    await user.update(ipss_test=new_ipss).apply()


async def update_user_qol(user_id, new_qol):
    user = await select_user(user_id)
    await user.update(qol_test=new_qol).apply()
